import random
import ConfigSpace as CS
import ConfigSpace.hyperparameters as CSH
import itertools

class Concat:
    cs_attributes = CS.ConfigurationSpace()
    attribute_list = ['axis']
    all_attributes = []

    def __init__(self):
        print('Concat Init--------------------------')
        self.init_all_attributes()
        self.init_cs()

    def init_all_attributes(self):
        for i in range(1, len(Concat.attribute_list)+1) :
            #此处取所有组合的可能值，存在列表里
            for attribute in itertools.combinations(Concat.attribute_list, i):
                l = list(attribute)
                Concat.all_attributes.append(l)

        #print('all_attributes: ', all_attributes)
        print('all attributes:')
        for a in Concat.all_attributes:
            print(a)

    def init_cs(self):
        length = len(Concat.all_attributes)
        attributes = CSH.UniformIntegerHyperparameter(name='combination', lower=0, upper=length)
        Concat.cs_attributes.add_hyperparameter(attributes)


    def get_random_combination(self):
        s = Concat.cs_attributes.sample_configuration()
        index = s.get_dictionary()['combination']
        print('get combination: ', index)

        length = len(Concat.all_attributes)

        #保证不带任何属性的case可以被覆盖到
        if index >= length:
            index = length - 1

        return Concat.all_attributes[index]       

    def get_max_attributes_combination(self):
        return len(Concat.all_attributes)

    def get_attributes_by_index_or_random(self, shapes, index):

        print('get_attributes_by_index_or_random, index: ', index)    
            
        attributes = {}
        shape_out = []

        print('Concat, shapes:', shapes[0])

        axis = 0

        if index != -1:
            attr_combination = Concat.all_attributes[index]
        else:
            attr_combination = self.get_random_combination()

        if len(attr_combination) == 0:
            return attributes, shape_out    

        if 'axis' in attr_combination:
            axis = random.randint(-1*len(shapes[0]), len(shapes[0]) - 1)
            attributes['axis'] = axis

        return attributes, shape_out 

    def input_shape_correct(self, shapes):
        shape = shapes[0]

        if len(shapes) > 1:
            for i in range(len(shapes), 1):
                shapes[i] = shape

        return True

    def get_input_name(self, index):
        return 'value' + str(index)

   